interface TableItem<T> {
  data: T[]
  loading: boolean
}

interface Result<T> {
  list: T[]
  total: number
}

/**
 * expand table
 * @returns
 */
export function useExpandTable<T extends any>(fn: () => Promise<Result<T>>) {
  const expandTable = reactive<Record<string, TableItem<T>>>({})

  function getExpandTable(id?: string) {
    const initItem: TableItem<T> = { data: [], loading: false }
    if (!id) return initItem
    if (!expandTable[id]) expandTable[id] = initItem
    return expandTable[id]
  }

  function setExpandTable<P extends T>(id: string, data: P[]) {
    const item = getExpandTable(id)
    item.data = data
    item.loading = false
  }

  async function fetchExpandTable(id: string) {
    const tableObject = getExpandTable(id)
    tableObject.loading = true
    try {
      const res = await fn()
      tableObject.data = res.list || []
    } catch (error) {
      tableObject.data = []
    } finally {
      tableObject.loading = false
    }
  }
  return { expandTable, getExpandTable, setExpandTable, fetchExpandTable }
}
